#1/usr/bin/python3
import os
import re
import shutil
tree = "/var/slackmaster"
work = "/tmp/slackmaster/work"
class NotString(Exception):
    pass

class NoMatch(Exception):
    pass

def search(script):
    try:
        if isinstance(script, str):
            
            file = open("{0}/SLACKBUILDS.TXT".format(tree), encoding="utf8")
            file = file.readlines()
            slist = []
            
            for lines in file:
                match = re.match("SLACKBUILD LOCATION: ..(\w+.*{0}.*)".format(re.escape(script)), lines)
                if match:
                    slist.append(match.group(1))

                else:
                    pass


            return slist


        else:
            pass

    except NoMatch:
        raise
            

def sub_list(list_to_check):
    newlist = []
    for elements in list_to_check:
        if isinstance(elements, str):
            newlist.append(elements)
            
        if isinstance(elements, list):
            newlist.extend(elements)

    return(newlist)
            
        
            
    
            

        
def strip_number_of_list(list):
    num_type = type(2)
    new_list = [number for number in list if type(number) != num_type]
    return new_list
        

def list_sbo_pkg():
    list = []
    for packages in os.listdir("/var/log/packages"):
        if re.match(".*SBo.*", packages):
            list.append(packages)
    return(list)

def path_exist():
    if os.path.exists(tree) == False:
        os.mkdir(tree)
    if os.path.exists(work) == False:
        os.makedirs(work)

def move_file_from_tree(script, dest):
    name = script.split("/")
    name = name[1]
    script_dir = os.listdir("{0}/{1}/".format(tree, script))
    for files in script_dir:
        os.chdir("{0}/{1}".format(tree, script))
        shutil.copy2(files, dest)

def main_dl_link(link):
    if link.startswith('DOWNLOAD="') or link.endswith('\\\n'):
        stripped_main_link = link.replace('DOWNLOAD="', '').replace('\\\n', '').replace('\n', '').replace('"', '').replace(' ', '')
        return stripped_main_link

def strip_dl_link(link):
    if link.startswith('\t') or link.endswith('\\\n'):
        stripped_link = link.replace('\t', '').replace('\\\n', '').replace('"', '').replace('\n', '').replace(' ', '')
        return stripped_link

def get_downloads_link(script):
    name = script.split("/")
    name = name[1]
    f = open("{0}/{1}/{2}.info".format(tree, script, name))
    file = f.readlines()
    dl_list = []
    stripped_dl_list = []
    for line in file:
        if line.startswith("\tftp") or line.startswith("\thttp") or line.startswith("DOWNLOAD="):
            dl_list.append(line)
    
    for main_download in dl_list:
        if main_download.startswith('DOWNLOAD="'):
            stripped_master_link = main_dl_link(main_download)
            stripped_dl_list.insert(0, stripped_master_link)

    for alternative_download in dl_list:
        if alternative_download.startswith("\tftp") or alternative_download.startswith("\thttp"):
            stripped_alternative_download = strip_dl_link(alternative_download)
            stripped_dl_list.append(stripped_alternative_download)
    return(stripped_dl_list)

def match_name_with_cat(script):
    try:
        pot_match = search(script)
        for elements in pot_match:
            if elements.endswith(script):
                return(elements)

    except:
        raise
